﻿using CookieApp.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace CookieApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : Controller
    {
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return $"value id = {id.ToString()}";
        }

        // POST api/<controller>
        [HttpPost]
        [Route("login")]
        public async Task<IActionResult> Post([FromForm] ApplicationUser user)
        {
            if (user.Name.Equals("admin"))
            {

                var lstClaims = new List<Claim>();

                user.Id = new Random().Next(1, 10);
                user.Email = user.Name + "@qq.com";

                lstClaims.Add(new Claim(ClaimTypes.Name, user.Name));
                lstClaims.Add(new Claim(ClaimTypes.Email, user.Email));
                lstClaims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

                var ClaimIdentities = new ClaimsIdentity(lstClaims, "auth");

                var claims = new ClaimsPrincipal(ClaimIdentities);

                await HttpContext.SignInAsync(claims);

                return Redirect("/");
            }
            else
            {
                return BadRequest("invalid user");
            }
        }

        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
